import React, { useMemo, useState, useEffect, SetStateAction } from 'react';
import { Drawer, message, Button, Table, Typography, Form, Empty } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { uuid, getDesignerShowType } from '@inbiz/utils';
import { useOperation, useWorkbench, getMessage, TextWidget } from '@inbiz/react';
import { schemaMap } from '@inbiz/render';
import Pagination from '@inbiz/basic/Pagination';
import { EditableRow, EditableCell } from './EditCell';
import { getVariateList, getPageDetails, saveVariate } from '../server';
import './style.less';
const { Text } = Typography;
interface DataType {
    id: SetStateAction<string>;
    key: string;
    name: string;
    age: number;
    address: string;
    tags: string[];
}

const EditableContext = React.createContext<any>(null);
export { EditableContext };

const SetVariableDrawer = (props: any) => {
    const { drawerParams, processId, processKey, appInfo, isNew, pageOutId } = props;
    const [loading, setLoading] = useState(false);
    const [variateList, setVariateList] = useState([]);
    const [isEmpty, setIsEmpty] = useState(true);
    const [variateSelectedRowKeys, setVariateSelectedRowKeys] = useState<any[]>([]);
    const [variateId, setVariateId] = useState('');
    const [delIds, setDelIds] = useState<any[]>([]);
    const [pcControl, setPcControl] = useState<any[]>([]);
    const [h5Control, setH5Control] = useState<any[]>([]);
    const [control, setControl] = useState<any[]>([]);
    const [saveLoading, setSaveLoading] = useState<boolean>(false);
    const [total, setTotal] = useState<number>(0);
    const [pageIndex, setPageIndex] = useState<number>(1);
    const [pageSize, setPageSize] = useState<number>(10);
    const [form] = Form.useForm();
    let workbench = null;
    let operation = null;
    if (getDesignerShowType() !== 3) {
        workbench = useWorkbench();
        const currentWorkspace = workbench?.activeWorkspace || workbench?.currentWorkspace;
        const currentWorkspaceId = currentWorkspace?.id;
        operation = useOperation(currentWorkspaceId);
    };

    const handleSave = (row: any) => {
        const newData: any = [...variateList];
        const index = newData.findIndex((item: { id: string }) => row.id === item.id);
        const item: any = newData[index];
        newData.splice(index, 1, {
            ...item,
            ...row,
        });
        setVariateList(newData);
    };

    const defaultColumn = useMemo(() => {
        if (isNew) {
            return [
                {
                    title: '变量名称',
                    dataIndex: 'varName',
                    editable: true,
                    required: true,
                    width: '25%',
                    ellipsis: true,
                },
                {
                    title: '变量类型',
                    dataIndex: 'type',
                    width: '22%',
                    render: (text: any) => {
                        if (text == 0) {
                            return '普通类型';
                        } else {
                            return '组件类型';
                        }
                    },
                    ellipsis: true,
                },
                {
                    title: '组件',
                    dataIndex: 'pcControlId',
                    editable: true,
                    width: '25%',
                    render: (txt: any, record: any) => {
                        return record.pcControl;
                    },
                    ellipsis: true,
                },
                {
                    title: '描述',
                    dataIndex: 'remark',
                    editable: true,
                    width: '28%',
                    render: (txt: any) => <Text ellipsis={{ tooltip: txt }}>{txt}</Text>,
                    ellipsis: true,
                },
            ];
        } else {
            return [
                {
                    title: '变量名称',
                    dataIndex: 'varName',
                    editable: true,
                    required: true,
                    width: '20%',
                    ellipsis: true,
                },
                {
                    title: '变量类型',
                    dataIndex: 'type',
                    width: '17%',
                    render: (text: any) => {
                        if (text == 0) {
                            return '普通类型';
                        } else {
                            return '组件类型';
                        }
                    },
                    ellipsis: true,
                },
                {
                    title: 'PC组件',
                    dataIndex: 'pcControlId',
                    editable: true,
                    width: '20%',
                    render: (txt: any, record: any) => {
                        return record.pcControl;
                    },
                    ellipsis: true,
                },
                {
                    title: 'H5组件',
                    dataIndex: 'moveControlId',
                    editable: true,
                    width: '20%',
                    render: (txt: any, record: any) => {
                        return record.moveControl;
                    },
                    ellipsis: true,
                },
                {
                    title: '描述',
                    dataIndex: 'remark',
                    editable: true,
                    width: '23%',
                    render: (txt: any) => <Text ellipsis={{ tooltip: txt }}>{txt}</Text>,
                    ellipsis: true,
                },
            ];
        };
    }, [isNew]);

    const columns: ColumnsType<DataType> = useMemo(() => {
        return defaultColumn.map((col) => {
            if (!col.editable) {
                return col;
            };
            if (isNew) {
                return {
                    ...col,
                    onCell: (record: any) => ({
                        record,
                        editable: col.editable,
                        dataIndex: col.dataIndex,
                        title: col.title,
                        required: col.required,
                        pcControl: control,
                        h5Control: control,
                        variateId: variateId,
                        setNowKey: (e: any) => setVariateId(e),
                        handleSave,
                    }),
                };
            } else {
                return {
                    ...col,
                    onCell: (record: any) => ({
                        record,
                        editable: col.editable,
                        dataIndex: col.dataIndex,
                        title: col.title,
                        required: col.required,
                        pcControl: pcControl,
                        h5Control: h5Control,
                        variateId: variateId,
                        setNowKey: (e: any) => setVariateId(e),
                        handleSave,
                    }),
                };
            };
        })
    }, [pcControl, h5Control, variateId, defaultColumn, isNew]);

    const onSelectChange = (newSelectedRowKeys: any) => {
        setVariateSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys: variateSelectedRowKeys,
        onChange: onSelectChange,
    };

    const components = {
        body: {
            row: EditableRow,
            cell: EditableCell,
        },
    };

    const addVariateRow = () => {
        let _variateList = variateList;
        setVariateList(_variateList.concat({
            id: uuid(20, 60),
            varName: '',
            type: '0',
            pcControl: '',
            pcControlId: '',
            moveControlId: '',
            moveControl: '',
            remark: '',
        }))
    };

    const delVariate = () => {
        if (variateSelectedRowKeys.length === 0) {
            message.error('请选择要删除的数据');
        } else {
            setVariateList(
                variateList.filter(
                    (item: any) => !variateSelectedRowKeys.includes(item.id),
                ),
            );
            setDelIds([...delIds, ...variateSelectedRowKeys]);
            setVariateSelectedRowKeys([]);
        }
    };

    const onCancel = () => {
        drawerParams?.onCancel && drawerParams?.onCancel();
    };

    const onSave = () => {
        let list: any[] = variateList?.map((item) => {
            if (isNew) {
                return {
                    id: item?.id,
                    varName: item?.varName,
                    type: '0',
                    pcControl: item?.pcControl,
                    pcControlId: item?.pcControlId,
                    moveControl: item?.moveControl,
                    moveControlId: item?.moveControlId,
                    remark: item?.remark,
                }
            } else {
                return item;
            };
        });
        let varNames: string[] = [];
        for (let i = 0; i < list.length; i++) {
            for (let j = 0; j < defaultColumn.length; j++) {
                if (defaultColumn[j].required) {
                    let key = defaultColumn[j].dataIndex;
                    if (!list[i][key] || list[i][key] === '') {
                        let dom = document.getElementById(`cell-${key}-${list[i].id}`);
                        dom?.click();
                        setTimeout(() => {
                            form.validateFields();
                        }, 0);
                        return;
                    }
                }
            }
            if (varNames.includes(list[i].varName)) {
                message.error('变量名称相同')
                return;
            }
            varNames.push(list[i].varName);
        }
        const dels: string[] = [...new Set(delIds)];
        variateSelectedRowKeys;
        let _data = {
            ids: dels.join(','),
            processId,
            vars: JSON.stringify(list),
        };
        setSaveLoading(true);
        saveVariate(_data).then((res: any) => {
            if (res.code == 200) {
                message.success('保存成功');
                onCancel();
            } else {
                message.error(res?.message || '保存失败');
            }
            setSaveLoading(false);
        });
    };

    const getVarList = async () => {
        setLoading(true);
        try {
            let varListResults = await getVariateList({ processId, pageIndex, pageSize });
            if (varListResults?.code == '200' && varListResults?.details?.rows && varListResults?.details?.rows?.length) {
                setIsEmpty(varListResults?.details?.rows?.legnth == 0);
                setVariateList(varListResults?.details?.rows || []);
                setTotal(varListResults?.details?.total);
            };
            if (isNew) {
                let pageDetails = schemaMap(operation.tree, true)?.map((item) => {
                    return {
                        ...item,
                        value: item?.value,
                        name: getMessage(item.name),
                    };
                });
                setControl(pageDetails);
            } else {
                let pcPageDetails = await getPageDetails({ ismove: false, processKey });
                if (pcPageDetails.details?.schema) {
                    let data = schemaMap(pcPageDetails.details?.schema);
                    const selectOption = data.map((item) => {
                        return {
                            ...item,
                            name: getMessage(item.name),
                        };
                    });
                    setPcControl(selectOption);
                };
                let h5PageDetails = await getPageDetails({ ismove: true, processKey });
                if (h5PageDetails.details?.content?.schema) {
                    let data = schemaMap(h5PageDetails.details?.content.schema);
                    const selectOption = data.map((item) => {
                        return {
                            ...item,
                            name: getMessage(item.name),
                        };
                    });
                    setH5Control(selectOption);
                };
            };
            setLoading(false);
        } catch (error: any) {
            message.error(error);
            setLoading(false);
        };
    };

    const onPageChange = (page: { current: number, pageSize: number }) => {
        setPageIndex(page?.current);
        setPageSize(page?.pageSize);
        setLoading(true);
        getVariateList({ processId, pageIndex: page?.current, pageSize: page?.pageSize }).then((res) => {
            if (res?.code == '200' && res?.details && res?.details?.rows && res?.details?.rows?.length) {
                setTotal(res?.details?.total);
                setVariateList(res?.details?.rows || []);
            } else {
                message.error(res?.message);
            };
            setLoading(false);
        })
    };

    useEffect(() => {
        getVarList();
    }, [isNew]);

    return (
        <Drawer
            {...drawerParams}
            title='设置变量'
            bodyStyle={{
                height: 'calc(100% - 55px)',
                padding: '20px 20px 0 20px',
            }}
        >
            <>
                <div className='process-designer-set-variable-drawer-buttons'>
                    <Button type='primary' onClick={addVariateRow}>添加</Button>
                    <Button danger onClick={delVariate}>删除</Button>
                </div>
                <div className='process-designer-set-variable-drawer-table-wrapper'>
                    <div className='process-designer-set-variable-drawer-table' >
                        <Form form={form}>
                            <EditableContext.Provider value={form}>
                                <Table
                                    rowSelection={rowSelection}
                                    components={components}
                                    columns={columns}
                                    dataSource={variateList}
                                    pagination={false}
                                    size="small"
                                    bordered
                                    rowKey="id"
                                    loading={loading}
                                    rowClassName={'process-designer-set-variable-drawer-table-row'}
                                    onRow={(record) => {
                                        return {
                                            onClick: () => {
                                                setVariateId(record?.id);
                                            },
                                        };
                                    }}
                                    locale={{
                                        emptyText: (
                                            <Empty
                                                image={Empty.PRESENTED_IMAGE_SIMPLE}
                                                description={<TextWidget>暂无数据</TextWidget>}
                                            />
                                        ),
                                    }}
                                />
                            </EditableContext.Provider>
                        </Form>
                    </div>
                    <Pagination
                        size='small'
                        options={[10, 20, 30, 40, 50]}
                        total={total}
                        current={pageIndex}
                        pageSize={pageSize}
                        onChange={onPageChange}
                        style={{ marginTop: 4, marginBottom: 4 }}
                    />
                </div>
                <div className='process-designer-set-variable-drawer-footer'>
                    <div>
                        <Button onClick={onCancel}>取消</Button>
                        <Button type='primary' onClick={onSave} loading={saveLoading}>确定</Button>
                    </div>
                </div>
            </>
        </Drawer>
    );
};

export default SetVariableDrawer